package day20210622;

import treenode.SimpleTreeNode;

/**
 * 108.将有序数组转换为二叉搜索树
 * @author lizy4
 * @className Solution
 * @date 2021/6/22 22:42
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums = {-10,-3,0,5,9};
        Solution solution = new Solution();
        System.out.println(solution.sortedArrayToBST(nums));
    }
    public SimpleTreeNode sortedArrayToBST(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }

    public SimpleTreeNode helper(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }

        // 总是选择中间位置左边的数字作为根节点
        int mid = (left + right) / 2;

        SimpleTreeNode root = new SimpleTreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        return root;
    }
}
